﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Driver;
using MongoDB.Bson;
using System.Text.RegularExpressions;
using System.Collections;
using MongoDB.Driver.Builders;
using NetMongo.Helper;
using NetMongo.Entity;

namespace NetMongo.Data
{
    public class MongodbBase<T> where T : IMongoEntity
    {
        public static IMongoDatabase db = null;
        private static IMongoCollection<T> collection;
        private static MongoUrlBuilder bldr = new MongoUrlBuilder();
        private static MongodbConfig Config = null;
        private static object Lock = new object();
        private static object Lock_Service = new object();
        private static List<MongoServerAddress> Servers = new List<MongoServerAddress>();
        protected void Init(string DbName)
        {
            try
            {
                if(db!=null)
                {
                    collection = db.GetCollection<T>(typeof(T).Name);
                    return;
                }
                
                if(Config==null)
                {
                    lock(Lock)
                    {
                        if (Config == null)
                        {
                            Config = ManagerConfig.ServiceSettings.mongodbs.Where(p => p.DBName == DbName).FirstOrDefault();
                        }
                    }
                }
                if(Servers==null|!Servers.Any())
                {
                    lock(Lock_Service)
                    {
                        if(Servers==null|!Servers.Any())
                        {
                            Servers.Add(new MongoServerAddress(Config.Host));
                        }
                    }
                }

                if (Config == null)
                {
                    throw new Exception("不存在数据库为: " + DbName + " 的配置对象，请检查");
                }
                else
                {
                    bldr.Username = Config.UserName;
                    bldr.Password = Config.Password;
                    bldr.Servers = Servers;
                    bldr.DatabaseName = Config.DBName;
                    bldr.AuthenticationMechanism = Config.AuthMechanism;
                    bldr.ReadPreference = ReadPreference.PrimaryPreferred;
                    var urlBuilder = new MongoUrlBuilder(bldr.ToMongoUrl().ToString());
                    //IMongoClient mc = new MongoClient(urlBuilder.ToMongoUrl());
                    IMongoClient mc = new MongoClient("mongodb://127.0.0.1:27017");
                    db = mc.GetDatabase(Config.DBName);
                    collection = db.GetCollection<T>(typeof(T).Name);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }

        #region 查询
        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public T Get(string Id)
        {
            try
            {
                return collection.Find<T>(a => a.Id == new ObjectId(Id).ToString()).FirstOrDefault();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return default(T);
            }
        }
        /// <summary>
        /// 获得一个对象信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public T Get(Expression<Func<T, bool>> exp)
        {
            return FirstOrDefault(exp);
        }
        public List<T> GetList(Expression<Func<T, bool>> exp)
        {
            try
            {
                return collection.Find<T>(exp).ToList();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }
        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<T> GetList(List<string> ids)
        {
            try
            {
                return collection.Find<T>(a => ids.Contains(a.Id)).ToList();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }

        /// <summary>
        /// 获取一条记录(自定义条件)
        /// </summary>
        /// <returns></returns>
        public T FirstOrDefault(Expression<Func<T, bool>> expression)
        {
            try
            {
                return collection.Find<T>(expression).FirstOrDefault();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return default(T);
            }
        }

        /// <summary>
        /// 获取一条记录
        /// </summary>
        /// <returns></returns>
        public T FirstOrDefault()
        {
            try
            {
                return collection.Find<T>(new BsonDocument()).FirstOrDefault();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return default(T);
            }
        }
        public T FirstOrDefault(Dictionary<string, object> WhereDict)
        {
            try
            {
                var querywhere = GetQueryDocument(WhereDict);
                return collection.Find<T>(querywhere).FirstOrDefault();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return default(T);
            }
        }

        /// <summary>
        /// 根据条件获取数量
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public long GetCount(Expression<Func<T, bool>> expression = null)
        {
            try
            {
                if (expression == null)
                {
                    return collection.Count(new BsonDocument());
                }
                else
                {
                    return collection.Count(expression);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return -1;
            }
        }

        /// <summary>
        /// 根据ID判断是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(string id)
        {
            try
            {
                return collection.Count(a => a.Id == new ObjectId(id).ToString()) > 0;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }

        public List<T> Search(int Skip, int Limit, string WhereJson = "", string OrderJson = "")
        {
            return FindAll(Skip, Limit, WhereJson, OrderJson);
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="Skip"></param>
        /// <param name="Limit"></param>
        /// <param name="exp"></param>
        /// <param name="OrderJson"></param>
        /// <returns></returns>
        public List<T> Search(int Skip, int Limit, Expression<Func<T, bool>> exp = null, string OrderJson = "")
        {
            return FindAll(Skip, Limit, exp, OrderJson);
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns></returns>
        public List<T> FindAll()
        {
            try
            {
                return collection.Find<T>(new BsonDocument()).ToList();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }

        /// <summary>
        /// 获取全部(自定义条件)
        /// </summary>
        /// <returns></returns>
        public List<T> FindAll(Expression<Func<T, bool>> expression)
        {
            try
            {
                return collection.Find<T>(expression).ToList();
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }

        /// <summary>
        /// 搜索数据
        /// </summary>
        /// <param name="Skip">排除前面多少条数据</param>
        /// <param name="Limit">获得接下来多少条数据</param>
        /// <param name="exp">过滤条件</param>
        /// <param name="orderjson">排序格式：{"name":-1,"age":1}  说明：1为升序，-1为降序</param>
        /// <returns></returns>
        public List<T> FindAll(int Skip, int Limit, Expression<Func<T, bool>> exp = null, string orderjson = "")
        {
            try
            {
                if (exp != null)
                {
                    if (Limit <= 0)
                    {
                        if (!string.IsNullOrEmpty(orderjson))
                        {
                            return collection.Find<T>(exp).Sort(orderjson).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(exp).ToList();
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(orderjson))
                        {
                            return collection.Find<T>(exp).Sort(orderjson).Skip(Skip).Limit(Limit).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(exp).Skip(Skip).Limit(Limit).ToList();
                        }
                    }
                }
                else
                {
                    if (Limit <= 0)
                    {
                        if (!string.IsNullOrEmpty(orderjson))
                        {
                            return collection.Find<T>(new BsonDocument()).Sort(orderjson).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(new BsonDocument()).ToList();
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(orderjson))
                        {
                            return collection.Find<T>(new BsonDocument()).Sort(orderjson).Skip(Skip).Limit(Limit).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(new BsonDocument()).Skip(Skip).Limit(Limit).ToList();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }

        /// <summary>
        /// 搜索数据
        /// </summary>
        /// <param name="Skip">排除前面多少条数据</param>
        /// <param name="Limit">获得接下来多少条数据(0:所有)</param>
        /// <param name="wherejson">条件格式：{"name":"Bruce","age":25}  </param>
        /// <param name="orderjson">排序格式：{"name":-1,"age":1}  说明：1为升序，-1为降序</param>
        /// <returns></returns>
        public List<T> FindAll(int Skip, int Limit, string wherejson = "", string orderjson = "")
        {
            try
            {
                if (Limit <= 0) Limit = 8000;
                if (Skip <= 0) Skip = 0;
                Dictionary<string, object> WhereDict = JsonHelper.DeserializeObject<Dictionary<string, object>>(wherejson);
                if (WhereDict != null && WhereDict.Count > 0)
                {
                    var bsonwhere = GetQueryDocument(WhereDict);

                    if (!string.IsNullOrEmpty(orderjson))
                    {
                        return collection.Find<T>(bsonwhere).Sort(orderjson).Skip(Skip).Limit(Limit).ToList();
                    }
                    else
                    {
                        return collection.Find<T>(bsonwhere).Skip(Skip).Limit(Limit).ToList();
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(orderjson))
                    {
                        return collection.Find<T>(new QueryDocument()).Sort(orderjson).Skip(Skip).Limit(Limit).ToList();
                    }
                    else
                    {
                        return collection.Find<T>(new QueryDocument()).Skip(Skip).Limit(Limit).ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }

        /// <summary>
        /// 搜索数据
        /// </summary>
        /// <param name="Skip">排除前面多少条数据</param>
        /// <param name="Limit">获得接下来多少条数据(0:所有)</param>
        /// <param name="exp">过滤条件</param>
        /// <param name="orderjson">排序格式：{"name":-1,"age":1}  说明：1为升序，-1为降序</param>
        /// <returns></returns>
        public List<T> FindAll(int Skip, int Limit, Dictionary<string, object> WhereDict = null, string OrderJson = "")
        {
            try
            {
                if (WhereDict != null && WhereDict.Count > 0)
                {
                    var querywhere = GetQueryDocument(WhereDict);
                    if (Limit <= 0)
                    {
                        if (!string.IsNullOrEmpty(OrderJson))
                        {
                            return collection.Find<T>(querywhere).Sort(OrderJson).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(querywhere).ToList();
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(OrderJson))
                        {
                            return collection.Find<T>(querywhere).Sort(OrderJson).Skip(Skip).Limit(Limit).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(querywhere).Skip(Skip).Limit(Limit).ToList();
                        }
                    }
                }
                else
                {
                    if (Limit <= 0)
                    {
                        if (!string.IsNullOrEmpty(OrderJson))
                        {
                            return collection.Find<T>(new BsonDocument()).Sort(OrderJson).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(new BsonDocument()).ToList();
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(OrderJson))
                        {
                            return collection.Find<T>(new BsonDocument()).Sort(OrderJson).Skip(Skip).Limit(Limit).ToList();
                        }
                        else
                        {
                            return collection.Find<T>(new BsonDocument()).Skip(Skip).Limit(Limit).ToList();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
        }
        #endregion

        #region 删除        
        /// <summary>
        /// 带条件的删除
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public void Delete(Expression<Func<T, bool>> expression)
        {
            try
            {
                collection.DeleteMany(expression);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }        

        /// <summary>
        /// 根据模型删除
        /// </summary>
        /// <param name="model"></param>
        public void Delete(T model)
        {
            try
            {
                var result = collection.DeleteOne(s => s.Id == new ObjectId(model.Id).ToString());
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="Id"></param>
        public bool Delete(string Id)
        {
            try
            {
               var result = collection.DeleteOne(s => s.Id == new ObjectId(Id).ToString());
                return result.DeletedCount > 0;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
            return false;
        }
        /// <summary>
        /// 全部删除
        /// </summary>
        /// <returns></returns>
        public void DeleteAll()
        {
            try
            {
                var result = collection.DeleteMany(new BsonDocument());
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        public void DeleteAll(List<T> model)
        {
            try
            {
                var Ids = model.Select(a => new ObjectId(a.Id).ToString()).ToList();
                var result = collection.DeleteMany(s => Ids.Contains(s.Id));
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }

        #endregion

        #region 添加
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Add(T model)
        {
            return Insert(model);
        }

        /// <summary>
        /// 添加数据返回model
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public T AddReturnModel(T model)
        {
            try
            {
                Insert(model);
                return model;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return default(T);
            }
        }
        /// <summary>
        /// 单模型添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Insert(T model)
        {
            try
            {
                collection.InsertOne(model);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool InsertBatch(List<T> model)
        {
            try
            {
                collection.InsertMany(model);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }
        #endregion

        #region 修改
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(T model)
        {
            try
            {
                collection.FindOneAndReplace<T>(s => s.Id == model.Id, model);
                return true;
            }
            catch (Exception err)
            {
                Logger.Log(err);
                return false;
            }
        }
        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public T UpdateReturnModel(T model)
        {
            try
            {
                return collection.FindOneAndReplace<T>(s => s.Id == model.Id, model);
            }
            catch (Exception err)
            {
                Logger.Log(err);
                return default(T);
            }
        }
        /// <summary>
        ///  更新一个对象多列数据
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="fieldparas"></param>
        /// <returns></returns>
        public bool Update(string Id, Dictionary<string, object> fieldparas)
        {
            try
            {
                var updatefields = new BsonDocument { { "$set", new BsonDocument(fieldparas) } };
                collection.UpdateOne(s => s.Id == Id, updatefields);
                return true;
            }
            catch (Exception err)
            {
                Logger.Log(err);
                return false;
            }            
        }
        /// <summary>
        /// 批量更新用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(List<T> model)
        {
            try
            {
                model.ForEach(e =>
                {
                    collection.FindOneAndReplace<T>(s => s.Id == e.Id, e);
                });
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }

        /// <summary>
        /// 更新一个实体多列数据
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="modelJson"></param>
        public void Update(string Id, string modelJson)
        {
            try
            {
                Dictionary<string, object> dictparams = JsonHelper.DeserializeObject<Dictionary<string, object>>(modelJson);
                var updatefields = new BsonDocument { { "$set", new BsonDocument(dictparams) } };
                collection.UpdateOne<T>(s => s.Id == Id, updatefields);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="model"></param>
        public void UpdateAll(List<T> model)
        {
            try
            {
                model.ForEach(e =>
                {
                    collection.FindOneAndReplace<T>(s => s.Id == e.Id, e);
                });
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        #endregion

        #region 正则表达式模糊查询
        private QueryDocument GetQueryDocument(Dictionary<string, object> WhereDict)
        {
            var result = new QueryDocument();
            //result.AddRange(Query.Exists("_id").ToBsonDocument());

            if (WhereDict != null && WhereDict.Count > 0)
            {
                Dictionary<string, object> Dict = new Dictionary<string, object>();
                foreach (var item in WhereDict)
                {
                    var obj = WhereDict[item.Key];
                    var strlist = new List<string>();
                    if (typeof(IList).IsAssignableFrom(obj.GetType()))
                    {
                        var dt = new List<DateTime>();
                        var numberlist = new List<Double>();
                        if (CommonHelper.IsDateTimeList(obj, out dt) && dt != null && dt.Count > 0)
                        {
                            if (dt.Count == 1)
                            {
                                var q = Query.EQ(item.Key, DateTime.Parse(dt[0].ToString()));
                                result.AddRange(q.ToBsonDocument());
                            }
                            else if (dt.Count == 2)
                            {
                                var q = Query.And(Query.GTE(item.Key, DateTime.Parse(dt[0].ToString())), Query.LT(item.Key, DateTime.Parse(dt[1].ToString())));
                                result.AddRange(q.ToBsonDocument());
                            }
                            else
                            {
                                List<BsonValue> bvlist = new List<BsonValue>();
                                dt.ForEach(s =>
                                {
                                    bvlist.Add(BsonValue.Create(DateTime.Parse(s.ToString())));
                                });
                                var q = Query.In(item.Key, bvlist);
                                result.AddRange(q.ToBsonDocument());
                            }
                        }
                        else if (CommonHelper.IsDoubleList(obj, out numberlist) && numberlist != null && numberlist.Count > 0)
                        {
                            if (numberlist.Count == 1)
                            {
                                var q = Query.EQ(item.Key, Double.Parse(numberlist[0].ToString()));
                                result.AddRange(q.ToBsonDocument());
                            }
                            else if (numberlist.Count == 2)
                            {
                                var q = Query.And(Query.GTE(item.Key, Double.Parse(numberlist[0].ToString())), Query.LT(item.Key, Double.Parse(numberlist[1].ToString())));
                                result.AddRange(q.ToBsonDocument());
                            }
                            else
                            {
                                List<BsonValue> bvlist = new List<BsonValue>();
                                numberlist.ForEach(s =>
                                {
                                    bvlist.Add(BsonValue.Create(Double.Parse(s.ToString())));
                                });
                                var q = Query.In(item.Key, bvlist);
                                result.AddRange(q.ToBsonDocument());
                            }
                        }
                        else if (CommonHelper.IsStringList(obj, out strlist) && strlist != null && strlist.Count > 0)
                        {
                            #region 使用正则查找
                            //string wheretype = string.Join("|", strlist).TrimEnd('|');
                            //Regex regex = new Regex(wheretype);
                            //var bsonregex = new BsonRegularExpression(regex);
                            //var q = Query.Matches(item.Key, bsonregex);
                            //result.AddRange(q.ToBsonDocument()); 
                            #endregion

                            if (strlist.Count == 1)
                            {
                                BsonValue bv = BsonValue.Create(strlist.FirstOrDefault());
                                var q = Query.EQ(item.Key, bv);
                                result.AddRange(q.ToBsonDocument());
                            }
                            else
                            {
                                List<BsonValue> bvlist = new List<BsonValue>();
                                strlist.ForEach(s =>
                                {
                                    bvlist.Add(BsonValue.Create(s));
                                });
                                var q = Query.In(item.Key, bvlist);
                                result.AddRange(q.ToBsonDocument());
                            }
                        }
                        else
                        {
                            string value = WhereDict[item.Key].ToString();
                            Regex regex = new Regex(value, RegexOptions.IgnoreCase);
                            var bsonregex = new BsonRegularExpression(regex);

                            var q = Query.Matches(item.Key, bsonregex);
                            result.AddRange(q.ToBsonDocument());
                        }
                    }
                    else if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
                    {
                        //建议统一进行OR查询条件时Dictionary<string, object>中Key == searchKeywords  ，object为：Dictionary<string, object>
                        object subobj = WhereDict[item.Key];                       
                        if (typeof(IDictionary).IsAssignableFrom(subobj.GetType()))
                        {
                            Dictionary<string, object> ordict = WhereDict[item.Key] as Dictionary<string, object>;
                            if (ordict != null && ordict.Count > 0)
                            {
                                List<IMongoQuery> mq = new List<IMongoQuery>();
                                foreach (var oq in ordict)
                                {
                                    mq.Add(Query.Matches(oq.Key, ordict[oq.Key].ToString().Replace("?", "")));
                                }
                                if (mq != null && mq.Count > 0)
                                {
                                    var q = Query.Or(mq);
                                    result.AddRange(q.ToBsonDocument());
                                }
                            }
                        }                       
                    }
                    else if (CommonHelper.IsStringList(obj, out strlist) && typeof(String).IsAssignableFrom(obj.GetType()) && strlist != null && strlist.Count > 0)
                    {
                        if (strlist.Count == 1)
                        {
                            BsonValue bv = BsonValue.Create(strlist.FirstOrDefault());
                            var q = Query.EQ(item.Key, bv);
                            result.AddRange(q.ToBsonDocument());
                        }
                        else
                        {
                            List<BsonValue> bvlist = new List<BsonValue>();
                            strlist.ForEach(s =>
                            {
                                bvlist.Add(BsonValue.Create(s));
                            });
                            var q = Query.In(item.Key, bvlist);
                            result.AddRange(q.ToBsonDocument());
                        }
                    }
                    else
                    {
                        if (item.Key.ToLower() == "id")
                        {
                            result.AddRange(Query.EQ("_id", ObjectId.Parse(WhereDict[item.Key].ToString())).ToBsonDocument());
                        }                        
                        else
                        {
                            if (WhereDict[item.Key].ToString().ToLower().Contains("$exists"))
                            {
                                result.AddRange(Query.Exists(item.Key).ToBsonDocument());
                            }
                            else if (WhereDict[item.Key].ToString().ToLower().Contains("$notexists"))
                            {
                                result.AddRange(Query.NotExists(item.Key).ToBsonDocument());
                            }
                            else if (WhereDict[item.Key].ToString().ToLower().Contains("$ne:"))
                            {
                                result.AddRange(Query.NE(item.Key, WhereDict[item.Key].ToString().Split(':')[1]).ToBsonDocument());
                            }
                            else
                            {
                                Type type = (obj.GetType());
                                switch (type.Name.ToLower())
                                {
                                    case "double":
                                    case "float":
                                    case "int":
                                    case "long":
                                    case "ulong":
                                    case "short":
                                    case "ushort":
                                    case "decimal":
                                        {
                                            result.AddRange(Query.EQ(item.Key, WhereDict[item.Key].ToString()).ToBsonDocument());
                                        }
                                        break;
                                    case "int32":
                                    case "int16":
                                    case "int64":

                                        {
                                            result.AddRange(Query.EQ(item.Key, int.Parse(WhereDict[item.Key].ToString())).ToBsonDocument());
                                        }
                                        break;
                                    case "char":
                                    case "guid":
                                    case "string":
                                        {
                                            result.AddRange(Query.Matches(item.Key, WhereDict[item.Key].ToString().Replace("?", "")).ToBsonDocument());
                                        }
                                        break;

                                    case "date":
                                    case "datetime":
                                        {
                                            result.AddRange(Query.EQ(item.Key, DateTime.Parse(WhereDict[item.Key].ToString())).ToBsonDocument());
                                        }
                                        break;
                                    default:
                                        result.AddRange(Query.EQ(item.Key, WhereDict[item.Key].ToString()).ToBsonDocument());
                                        break;
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        #endregion

        #region 集合操作
        /// <summary>
        /// 删除集合
        /// </summary>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public bool ExistCollection(string collectionName)
        {
            try
            {
                var collection = db.GetCollection<T>(collectionName);
                return collection != null;                
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }
        /// <summary>
        /// 删除集合
        /// </summary>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public bool DropCollection(string collectionName)
        {
            try
            {                
                db.DropCollection(collectionName);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }

        /// <summary>
        /// 新建集合
        /// </summary>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public bool CreateCollection(string collectionName)
        {
            try
            {
                db.CreateCollection(collectionName);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }
        }
        #endregion
    }
}